package com.linkhub.oms.admin.config.forest.interceptor;

import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.common.constant.ShopifyConstant;
import com.linkhub.oms.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import static com.linkhub.oms.common.constant.ShopifyConstant.SHOPIFY_URL_KEY;

/**
 * @Description: AuthenticationErrorInterceptor
 * @Author: echo
 * @Date: 2024/3/21 20:42
 * @Version: 1.0
 */
@Slf4j
public class AuthenticationErrorInterceptor implements Interceptor<ForestResponse<?>> {

    @Override
    public void afterExecute(ForestRequest request, ForestResponse response) {
        String url = request.getUrl();
        if (url.contains(SHOPIFY_URL_KEY)
                && StringUtils.isBlank(getAccessToken(request))
                && response.getStatusCode() == ShopifyConstant.AUTHORIZATION_CODE_EXPIRE_STATUS_CODE) {
            throw ExceptionFactory.getI18nBizException("shopify.api.authenticationCode.error");
        }


        if (!response.statusOk()) {
            throw new BizException(response.getContent());
//            throw ExceptionFactory.getI18nBizException("shopify.api.responseCode.error");
        }
    }


    private String getAccessToken(ForestRequest request) {
        return request.getHeaderValue(ShopifyConstant.ACCESS_TOKEN_HEADER);

    }
}
